<template>
	<view>
		<view class="u-p-15 cbg-white u-m-t-15">
			<view class="cflex-r u-p-l-20 u-p-r-20 u-p-t-15 u-p-b-15" style="align-items: center;">
				<view class="u-p-r-30 " style="font-weight: bold;">
					真实姓名
				</view>
				<view>
					<input placeholder="请输入真实姓名" v-model="userInfo.name" :disabled="status===0 || status===1"
						@tap="changeName()" />
				</view>
			</view>

			<view class="u-p-t-15 u-p-b-15">
				<u-divider :use-slot="false" half-width="350"></u-divider>
			</view>
			<view class="cflex-r u-p-l-20 u-p-r-20 u-p-t-15 u-p-b-15" style="align-items: center;"
				@tap="changeKeyboard()">
				<view class="u-p-r-30" style="font-weight: bold;">
					身份证号
				</view>
				<view>
					<input placeholder="请输入18位身份证号" v-model="userInfo.IDCard" maxlength="18" disabled="true"
						type="idcard" />
					<u-keyboard ref="uKeyboard" mode="card" v-model="Keyboard" @change="valChange"
						@backspace="backSpace()"></u-keyboard>
				</view>
			</view>
			<view class="u-p-t-15 u-p-b-15">
				<u-divider :use-slot="false" half-width="350"></u-divider>
			</view>
			<view class="cflex-r u-p-l-20 u-p-r-20 u-p-t-15 u-p-b-15" style="align-items: center;">
				<view class="u-p-r-30 " style="font-weight: bold;">
					邀请人电话
				</view>
				<view>
					<input placeholder="请输入邀请人电话" v-model="userInfo.phone" :disabled="status===0 || status===1"
						@tap="changeName()" />
				</view>
			</view>
		</view>

		<view class="u-m-t-15 cbg-white u-p-20">
			<view class="cflex-r u-p-l-20 u-p-r-20 u-p-t-15 u-p-b-15" style="align-items: center;">
				<view class="u-p-r-30 " style="font-weight: bold;">
					上传本人照片
				</view>
			</view>
			<view class="cflex-r" style="background-color: white;width:710rpx;height:300rpx;">
				<view class="cflex-c" style="align-items: center;position:relative;
				width:355rpx;" @tap="changeHead()">
					<view style="position: absolute;top:45rpx;left:78rpx;">
						<image v-show="jishiInfo.avatar!==null" :src="jishiInfo.avatar" mode="scaleToFill"
							style="width:215rpx;height:140rpx;border-radius: 10rpx;">
							<image v-show="jishiInfo.avatar===null" src="../../static/my/card0.png"
								style="width:215rpx;height:140rpx;"></image>
							<view class="u-m-t-30" style="color: #aaaaaa;">
								上传本人照片
							</view>
					</view>
				</view>
			</view>
		</view>

		<view class="u-m-t-15 cbg-white u-p-20">
			<view class="cflex-r u-p-l-20 u-p-r-20 u-p-t-15 u-p-b-15" style="align-items: center;">
				<view class="u-p-r-30 " style="font-weight: bold;">
					上传身份证照片
				</view>
			</view>
			<view class="cflex-r" style="background-color: white;width:710rpx;height:300rpx;">
				<view class="cflex-c" style="align-items: center;position:relative;
				width:355rpx;" @tap="upFront()">
					<view style="position: absolute;top:45rpx;left:78rpx;">
						<image v-show="userInfo.IDCardFront!==''" :src="userInfo.IDCardFront" mode="scaleToFill"
							style="width:215rpx;height:140rpx;border-radius: 10rpx;">
							<image v-show="userInfo.IDCardFront===''" src="../../static/my/card0.png"
								style="width:215rpx;height:140rpx;"></image>
							<view class="u-m-t-30" style="color: #aaaaaa;">
								上传身份证人像面
							</view>
					</view>
					<!-- <image v-if="userInfo.IDCardFront != '' " :src="userInfo.IDCardFront" style="width: 374rpx;height: 236rpx;"></image>
					<image v-else src="../../static/my/card0.png" style="width: 374rpx;height: 236rpx;"></image>
					<view style="color: #aaaaaa;">
						上传身份证人像面
					</view> -->
				</view>
				<view class="cflex-c" style="align-items: center;position: relative;
				width:355rpx;" @tap="upBack()">
					<view style="position: absolute;top:45rpx;right:80;">
						<image v-show="userInfo.IDCardBack!==''" :src="userInfo.IDCardBack" mode="scaleToFill"
							style="width:215rpx;height:140rpx;border-radius: 10rpx;">
							<image v-show="userInfo.IDCardBack===''" src="../../static/my/card.png"
								style="width:215rpx;height: 140rpx;"></image>
							<view class="u-m-t-30" style="color: #aaaaaa;">
								上传身份证国徽面
							</view>
					</view>
					<!-- <image v-if="userInfo.IDCardFront != '' " :src="userInfo.IDCardFront" style="width: 330rpx;height: 207rpx;"></image>
					<image v-show="userInfo.IDCardBack===''" src="../../static/my/card.png" style="width: 374rpx;height: 236rpx;"></image>
					<view style="color: #aaaaaa;">
						上传身份证国徽面
					</view> -->
				</view>
			</view>
		</view>

		<view class="u-m-20 u-m-t-80" style="margin-top: 200rpx;" v-if="status < 0 || status == 2">
			<u-button :hair-line="false" :custom-style="btn" @click="saveIDCard()">提交认证</u-button>
		</view>

	</view>
</template>

<script>
	import store from "@/store/index.js"
	export default {
		data() {
			return {
				btn: {
					backgroundColor: "#2869FE",
					color: '#333333'
				},
				Keyboard: false,
				userInfo: {
					name: "", //姓名
					age: '',
					sex: '',
					IDCard: "", //身份证号
					IDCardFront: "", //身份证正面地址
					frontRes: {}, //正面信息存储
					IDCardBack: "", //身份证反面地址
					backRes: {}, //背面信息存储
					phone: ''
				},
				jishiInfo: {
					avatar: '',
				},
				isSubmitting: false, 
				id: '',
				status: -1, //-1和2可输入

			}
		},
		onLoad() {
			this.onRequest()
			this.httpRequest();
		},
		methods: {
			httpRequest() { //获取数据
				this.$request("worker/other/selectWorker").then(res => {
					this.jishiInfo.avatar = res.data.avatar;
				});
			},
			changeID(event) { //更改身份证号时只能输入数字或X
				setTimeout(() => {
					if (this.userInfo.IDCard.length === 18) {
						this.userInfo.IDCard = this.userInfo.IDCard.replace(/[\Wa-wyz_]/gi, '');
					} else {
						this.userInfo.IDCard = this.userInfo.IDCard.replace(/\D/gi, '');
					}
				}, 100)
			},
			myUpImg(res) { //上传文件
				let that = this;
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: that.$store.state.baseUrl + "common/up/single",
						filePath: res.tempFilePaths[0],
						name: 'file',
						formData: {
							imgPath: res.tempFilePaths[0],
						},
						success(res1) {
							resolve(res1)
						},
						fail(err) {
							reject(err)
						}
					})
				})
			},
			changeName() {
				if (this.status == 0 || this.status == 1) {
					uni.showToast({
						title: "审核中或已认证将不能修改",
						icon: 'none'
					})
					return
				}
			},


			async changeHead() { //修改头像
				let that = this;
				if (this.status == 0 || this.status == 1) {
					uni.showToast({
						title: "审核中或已认证将不能修改",
						icon: 'none'
					})
					return
				}
				let imgRes = await this.myChooseImg(1);
				let upRes = await this.myUpImg(imgRes);
				upRes = JSON.parse(upRes.data);
				this.jishiInfo.avatar = upRes.url;
				let obj = {
					avatar: upRes.url
				}
				this.$request("worker/other/updateWorker", obj).then(res => {
					console.log("update", res)
				});
				this.$forceUpdate()
			},
			myUpImg(res) { //上传文件
				let that = this;
				return new Promise((resolve, reject) => {
					uni.uploadFile({
						url: that.$store.state.baseUrl + "common/up/single",
						filePath: res.tempFilePaths[0],
						name: 'file',
						formData: {
							imgPath: res.tempFilePaths[0],
						},
						success(res1) {
							resolve(res1)
						},
						fail(err) {
							reject(err)
						}
					})
				})
			},
			myChooseImg(flag) { //选择图片

				let mySourceType = ['album'];
				return new Promise((reslove, rejuct) => {
					if (flag === 1) {
						mySourceType = ['album', 'camera'];
					}
					uni.chooseImage({
						count: 1, //默认9
						sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
						sourceType: mySourceType, //从相册选择
						success(res) {
							reslove(res)
						},
						fail(err) {
							rejuct(err)
						}
					})
				})
			},






			upFront() { //人像面选择
				let that = this;
				if (this.status == 0 || this.status == 1) {
					uni.showToast({
						title: "审核中或已认证将不能修改",
						icon: 'none'
					})
					return
				}
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					async success(res) {
						that.userInfo.frontRes = res;
						that.userInfo.IDCardFront = res.tempFilePaths[0];
					}
				})
			},
			upBack() { //国徽面选择
				let that = this;
				if (this.status == 0 || this.status == 1) {
					uni.showToast({
						title: "审核中或已认证将不能修改",
						icon: 'none'
					})
					return
				}
				uni.chooseImage({
					count: 1, //默认9
					sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
					sourceType: ['album', 'camera'], //从相册选择
					async success(res) {
						that.userInfo.backRes = res;
						that.userInfo.IDCardBack = res.tempFilePaths[0];
					}
				})
			},
			changeKeyboard() { //是否显示软键盘
				if (this.status == 0 || this.status == 1) {
					uni.showToast({
						title: "审核中或已认证将不能修改",
						icon: 'none'
					})
					return
				} else {
					this.Keyboard = true;
				}
			},
			valChange(val) { //val表示输入的单个字符
				if (this.userInfo.IDCard.length < 18) { //这里为18是因为17位进入if后，就变成了18位
					if ((val === 'x' || val === 'X') && this.userInfo.IDCard.length === 17) {
						this.userInfo.IDCard += val;
					}
					if (val !== 'x' && val !== 'X')
						this.userInfo.IDCard += val;
				}
			},
			backSpace() {
				this.userInfo.IDCard = this.userInfo.IDCard.slice(0, this.userInfo.IDCard.length - 1);
			},
			async saveIDCard() {
				let that = this 
			  // 1. 检查是否处于锁定状态
			  if (this.isSubmitting) {
			    uni.showToast({
			      title: "提交中，请稍候...",
			      icon: "none",
			      duration: 2000,
			    });
			    return; // 直接返回，阻止重复执行
			  }
			
			  // 2. 标记为锁定状态
			  this.isSubmitting = true;
			
			  try {
			    // 3. 原有提交逻辑（包裹在 try-catch 中处理异常）
			    // 上传身份证正反面图片
			    const fRes = await this.myUpImg(this.userInfo.frontRes);
			    const bRes = await this.myUpImg(this.userInfo.backRes);
			    const fResData = JSON.parse(fRes.data);
			    const bResData = JSON.parse(bRes.data);
			    const aPhoto = fResData.url;
			    const bPhoto = bResData.url;
			
			    // 构建提交参数
			    const obj = {
			      name: this.userInfo.name,
			      code: this.userInfo.IDCard,
			      aPhoto,
			      bPhoto,
			      wId: store.state.wId,
			      wName: store.state.wName,
			      phone: this.userInfo.phone,
			    };
			
			    // 检查必填字段
			    for (const k in obj) {
			      if (obj[k] === "" || that.jishiInfo.avatar === "") {
			        uni.showToast({
			          title: "请填写完整信息",
			          icon: "none",
			        });
			        that.isSubmitting = false; // 重置锁定状态
			        return;
			      }
			    }
			
			    // 调用接口提交认证
			    const renZhengRes = await that.$request("worker/other/renZheng", obj);
			    if (renZhengRes.code === 500) {
			      uni.showToast({
			        title: renZhengRes.msg,
			        icon: "none",
			      });
			      that.isSubmitting = false; // 失败后重置锁定状态
			      return false;
			    }
			
			    // 提交成功，跳转页面
			    uni.showToast({
			      title: "提交成功，正在审核...",
			      icon: "none",
			    });
			    setTimeout(() => {
			      uni.switchTab({
			        url: "/pages/tab4",
			      });
			    }, 1000);
			  } catch (error) {
			    // 处理异常（如网络错误）
			    uni.showToast({
			      title: "提交失败，请重试",
			      icon: "none",
			    });
			    that.isSubmitting = false; // 异常后重置锁定状态
			  } finally {
			    // 3秒后自动解锁（无论成功或失败）
			    setTimeout(() => {
			      that.isSubmitting = false;
			    }, 3000);
			  }
			},
			//通过身份证号计算年龄、性别、出生日期
			idCard(userCard) {
				//获取性别
				var reg = /(^\\d{15}$)|(^\\d{17}([0-9]|X)$)/;
				if (reg.test(IDCard)) {
					if (parseInt(userCard.substr(16, 1)) % 2 == 1) {
						this.userInfo.sex = 2
					} else {
						this.userInfo.sex = 1
					}
					var myDate = new Date();
					var month = myDate.getMonth() + 1;
					var day = myDate.getDate();
					var age = myDate.getFullYear() - UUserCard.substring(6, 10) - 1;
					if (userCard.substring(10, 12) < month || userCard.substring(10, 12) == month && userCard.substring(12,
							14) <= day) {
						age++;
					}
					this.userInfo.age = age;
				} else {
					uni.showToast({
						title: '请输入正确的身份证号',
						icon: 'none'
					})
					return false
				}
			},
			onRequest() {
				this.$request("worker/other/getRenZheng", {}).then(res => {
					if (res.data) {
						var model = res.data
						this.status = model.authStatus;
						// this.status=-1;
						// model.authStatus=-1;
						if (model.authStatus == 2) {
							uni.showModal({
								title: '审核未通过，请重新提交审核',
								content: model.authCause, //未通过原因
								showCancel: false
							})
							this.id = model.id
							return
						} else if (model.authStatus == 0) {
							uni.showModal({
								title: '正在审核，请耐心等待',
								content: "",
								showCancel: false
							})
							this.userInfo.name = model.name
							this.userInfo.IDCard = model.code
							this.userInfo.IDCardFront = model.codeAPhoto
							this.userInfo.IDCardBack = model.codeBPhoto
							this.userInfo.phone = model.inviter
							this.id = model.id
							setTimeout(() => {
								uni.switchTab({
									url: '/pages/tab4'
								})
							}, 1000)
							return
						} else if (model.authStatus == 1) {
							uni.showToast({
								title: '已认证',
							})
							this.userInfo.name = model.name
							this.userInfo.IDCard = model.code
							this.userInfo.IDCardFront = model.codeAPhoto
							this.userInfo.IDCardBack = model.codeBPhoto
							this.id = model.id
							return
						}
					}
					console.log(res);
				});
			}

		}
	}
</script>

<style>

</style>